package com.ruoyi.am.controller;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import com.ruoyi.am.domain.AmRoster;
import com.ruoyi.am.utils.BeanUtil;
import com.ruoyi.am.utils.PasswordUtil;
import com.ruoyi.common.exception.BusinessException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.am.domain.AmDriver;
import com.ruoyi.am.service.IAmDriverService;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 司机信息Controller
 * 
 * @author hkkk
 * @date 2020-12-19
 */
@Controller
@RequestMapping("/am/driver")
public class AmDriverController extends BaseController
{
    private String prefix = "am/driver";
    private double apk_version;

    @Autowired
    private IAmDriverService amDriverService;
    @Autowired
    private IAmDriverService iAmDriverService;
    @Autowired
    private AmRosterController AmRoster;

    private final static Map<Long, AmDriver> users = new LinkedHashMap<Long, AmDriver>();
    {
    }

    @RequiresPermissions("am:driver:view")
    @GetMapping()
    public String driver()
    {
        return prefix + "/driver";
    }

    /**
     * 查询司机信息列表
     */
    @RequiresPermissions("am:driver:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(AmDriver amDriver)
    {
        startPage();
        List<AmDriver> list = amDriverService.selectAmDriverList(amDriver);
        return getDataTable(list);
    }

    /**
     * 导出司机信息列表
     */
    @RequiresPermissions("am:driver:export")
    @Log(title = "司机信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(AmDriver amDriver)
    {
        List<AmDriver> list = amDriverService.selectAmDriverList(amDriver);
//        for(AmDriver amDriver1:list){
//            amDriver1.setIdCard(amDriver1.getCarId()+"\t");
//        }
        ExcelUtil<AmDriver> util = new ExcelUtil<AmDriver>(AmDriver.class);
        return util.exportExcel(list, "driver");
    }

    /**
     * 新增司机信息
     */
    @GetMapping("/add")
    public String add()
    {
        return prefix + "/add";
    }

    /**
     * 新增保存司机信息
     */
    @RequiresPermissions("am:driver:add")
    @Log(title = "司机信息", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    @Transactional
    public AjaxResult addSave(AmDriver amDriver)
    {
        try {
            amDriver.setPassword(PasswordUtil.upPassword(amDriver.getPassword()));
            return toAjax(amDriverService.insertAmDriver(amDriver));
        }
        catch (Exception e){
            e.printStackTrace();
            return AjaxResult.error();
        }
    }

    /**
     * 修改司机信息
     */
    @GetMapping("/edit/{driverId}")
    public String edit(@PathVariable("driverId") Long driverId, ModelMap mmap)
    {
        AmDriver amDriver = amDriverService.selectAmDriverById(driverId);
        mmap.put("amDriver", amDriver);
        return prefix + "/edit";
    }

    /**
     * 修改保存司机信息
     */
    @RequiresPermissions("am:driver:edit")
    @Log(title = "司机信息", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(AmDriver amDriver)
    {
        try {
            amDriver.setPassword(PasswordUtil.upPassword(amDriver.getPassword()));
            return toAjax(amDriverService.updateAmDriver(amDriver));
        } catch (NoSuchAlgorithmException | UnsupportedEncodingException e) {
            e.printStackTrace();
            return AjaxResult.error();
        }
    }

    /**
     * 删除司机信息
     */
    @RequiresPermissions("am:driver:remove")
    @Log(title = "司机信息", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(amDriverService.deleteAmDriverByIds(ids));
    }

    @GetMapping("/getDriverNameList")
    @ResponseBody
    public AjaxResult getNameList(){
        AmDriver amDriver=new AmDriver();
        List<AmDriver> list = amDriverService.selectAmDriverList(amDriver);
        List<String> names=new ArrayList<>();
        for(AmDriver amDriver1:list){
            names.add(amDriver1.getName());
        }
        return AjaxResult.success(names);
    }

    @PostMapping("/updatePW")
    @ResponseBody
    public int updatePW(@RequestParam String data){

        String[] split_data=data.split("\\;");

        int id=Integer.parseInt(split_data[0]);
        String old_pw=split_data[1];
        String new_pw=split_data[2];

        AmDriver amDriver=amDriverService.selectAmDriverById((long)id);
        if(amDriver!=null) {
            try {
                if (amDriver.getPassword().equals(PasswordUtil.upPassword(old_pw))) {
                    amDriver.setPassword(PasswordUtil.upPassword(new_pw));
                    amDriverService.updateAmDriver(amDriver);
                    return 0;
                } else {
                    return -1;
                }
            } catch (Exception e) {
                e.printStackTrace();
                return 1;
            }
        }
        else
            return 1;
    }

    @PostMapping("/setVersion")
    @ResponseBody
    public void setApk(double version){
        apk_version=version;
    }

    @GetMapping("/getVersion")
    @ResponseBody
    public double getApk(){
        return apk_version;
    }

    @PostMapping("/login")
    @ResponseBody
    public AjaxResult login(@RequestParam String driver_id,String password){

        List<AmDriver> list=amDriverService.selectAmDriverList(new AmDriver());

        for(AmDriver amDriver:list){
            try {
                if(driver_id.equals(amDriver.getDriverNum())&&PasswordUtil.pdIsTrue(amDriver.getPassword(),password)){
                    return AjaxResult.success(amDriver);
                }
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            } catch (NoSuchAlgorithmException e) {
                e.printStackTrace();
            }
        }

        return AjaxResult.error("密码错误");

    }

    @PostMapping("/getError")
    @ResponseBody
    public String getError(String msg){

        System.out.println(DateUtils.dateTimeNow("yyyy-MM-dd HH:mm"));
        System.out.println(msg);

        return "成功!";
    }

    @PostMapping("/importData")
    @ResponseBody
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception
    {
        ExcelUtil<AmDriver> util = new ExcelUtil<AmDriver>(AmDriver.class);
        List<AmDriver> userList = util.importExcel(file.getInputStream());
        String message = importUser(userList, updateSupport);
        return AjaxResult.success(message);
    }

    public String importUser(List<AmDriver> userList, Boolean isUpdateSupport)
    {
        if (StringUtils.isNull(userList) || userList.size() == 0)
        {
            throw new BusinessException("导入用户数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (AmDriver user : userList)
        {
            try
            {
                // 验证是否存在这个用户
                boolean userFlag = false;
                if (amDriverService.selectAmDriverByNum(user.getDriverNum())!=null)
                {
                    userFlag = true;
                    break;
                }
                if (!userFlag)
                {
                    user.setPassword(PasswordUtil.upPassword(user.getPassword()));
                    amDriverService.insertAmDriver(user);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、用户 " + user.getName() + " 导入成功");
                }
                else
                {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、用户 " + user.getName() + " 已存在");
                }
            }
            catch (Exception e)
            {
                failureNum++;
                String msg = "<br/>" + failureNum + "、账号 " + user.getName() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
            }
        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new BusinessException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    @GetMapping("/importTemplate")
    @ResponseBody
    public AjaxResult importTemplate()
    {
        ExcelUtil<AmDriver> util = new ExcelUtil<AmDriver>(AmDriver.class);
        return util.importTemplateExcel("司机模板");
    }


}
